package com.gcloud.mesh.dcs.strategy.aliyun;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gcloud.mesh.asset.dao.CloudResourceDao;
import com.gcloud.mesh.asset.dao.NodeDao;
import com.gcloud.mesh.asset.entity.CloudResourceEntity;
import com.gcloud.mesh.dcs.strategy.IReleaseNode;
import com.gcloud.mesh.framework.core.util.JsonUtil;
import com.gcloud.mesh.header.vo.asset.NodeItemVo;
import com.gcloud.mesh.supplier.adapter.AliPowerConsumptionAdapter;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class AliyunReleaseNode implements IReleaseNode{
	@Autowired
	private AliPowerConsumptionAdapter aliPowerConsumptionAdapter;
	
	@Autowired
	private NodeDao nodeDao;
	
	@Autowired
	private CloudResourceDao cloudResourceDao;
	/**
	 * 调用阿里的接口释放资源，当当前节点没有应用的时候释放节点
	 * @param nodeId
	 */
	@Override
	public void releaseNode(String nodeId) {
		try {
			log.info("开始释放阿里云的节点{}",nodeId);
			NodeItemVo nodeVo = nodeDao.getById(nodeId, null, NodeItemVo.class);
			//这里判断当前节点是否还有应用，没有应用释放节点
			Map<String, Object> param = new HashMap<>();
			Map<String, String> expand = new HashMap<>(); 
			expand.put("nodeId", nodeId);
			String value = JsonUtil.toJSONObject(expand).toJSONString();
			param.put("expand", value);
			List<CloudResourceEntity>  cloudResources = cloudResourceDao.findByProperties(param);
			if(cloudResources ==  null || cloudResources.isEmpty()) {
				String esn = nodeVo.getEsn();
				aliPowerConsumptionAdapter.releaseDevice(esn);
			}else {
				log.info("节点还存在应用，暂时不释放{}",nodeId);
			}
		} catch (Exception e) {
			log.error("释放阿里云的esn资源失败",e);
		}
	}
}
